package com.dxy.authresource.core;

import com.dxy.authresource.annotation.AuthResource;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.AbstractHandlerMethodMapping;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * Created by cxf_dxy on 2018/10/29.
 */
public class DataBuilder {

    public static Map build(Map.Entry<?, HandlerMethod> method, Map.Entry<String, AbstractHandlerMethodMapping> bean){
        Map<String, Object> map = new HashMap<>();
        RequestMappingInfo info = (RequestMappingInfo) method.getKey();
        map.put("bean", bean.getKey());
        map.put("method", method.getValue().toString());
        String auth = "N";
        String name = info.getName();
        AuthResource authResouce = method.getValue().getMethodAnnotation(AuthResource.class);
        if (authResouce != null && !authResouce.name().isEmpty()) {
            name = authResouce.name();
            auth = "Y";
        }
        map.put("name", name);
        map.put("auth", auth);
        map.put("path", convertPatterns(info.getPatternsCondition().getPatterns()));
        map.put("http_method", convertMethods(info.getMethodsCondition().getMethods()));
        return  map;
    }


    private static String convertPatterns(Set<String> patterns){
        String result = "";
        for(String s : patterns){
            result += s +",";
        }
        if(result.equals("")) return result;
        return result.substring(0,result.lastIndexOf(","));
    }


    private static String convertMethods(Set<RequestMethod> methods){
        String result = "";
        for(RequestMethod s : methods){
            result += s.name() +",";
        }
        if(result.equals("")) return result;
        return result.substring(0,result.lastIndexOf(","));
    }
}
